<?php namespace Phpcmf\Controllers\Admin;

class Son extends \Phpcmf\Admin\Mform
{

    public function index() {
        if ($_GET['keyword']) {
            $this->_Admin_List();
        } else {
            $this->init['order_by'] = 'displayorder asc,id asc';
            list($tpl, $data) = $this->_List(['cid' =>  $this->cid], -1);
            \Phpcmf\Service::V()->assign([
                'p' => ['cid' =>  $this->cid],
                'list' => dr_format_son_list($data['list'], $this->index['son_type']),
                'stype' => dr_son_type($this->index['son_type']),
            ]);
            \Phpcmf\Service::V()->display('son_list.html');
        }
    }

    public function add() {
        $this->_Admin_Add();
    }

    public function edit() {
        $this->_Admin_Edit();
    }

    public function show_index() {
        $this->_Admin_Show();
    }

    public function order_edit() {
        $this->_Admin_Order();
    }

    public function del() {
        $this->_Admin_Del();
    }


    // 隐藏或者启用
    public function vip_edit() {

        $id = (int)\Phpcmf\Service::L('Input')->get('id');
        $row =\Phpcmf\Service::M()->table($this->init['table'])->get($id);
        !$row && $this->_json(0, dr_lang('数据不存在'));

        $v = $row['vip'] ? 0 : 1;
        \Phpcmf\Service::M()->table($this->init['table'])->update($id, ['vip' => $v]);

        exit($this->_json(1, dr_lang($v ? '已设置收费' : '已设置免费'), ['value' => $v]));
    }

    // 分类操作
    public function son_add() {

        if (IS_POST) {
            $name = dr_safe_replace($_POST['name']);
            !$name && $this->_json(0, dr_lang('名称没有填写'));
            $stype = dr_son_type($this->index['son_type']);
            $stype[] = $name;
            \Phpcmf\Service::M()->table(dr_module_table_prefix(APP_DIR))->update($this->cid, [
                'son_type' => dr_array2string($stype)
            ]);
            $this->_json(1, dr_lang('操作成功'));
        }

        \Phpcmf\Service::V()->assign([
            'value' => '',
        ]);
        \Phpcmf\Service::V()->display('son_name.html');exit;
    }

    public function son_edit() {

        $tid = intval($_GET['tid']);
        $stype = dr_son_type($this->index['son_type']);

        if (IS_POST) {
            $name = dr_safe_replace($_POST['name']);
            !$name && $this->_json(0, dr_lang('名称没有填写'));
            $stype[$tid] = $name;
            \Phpcmf\Service::M()->table(dr_module_table_prefix(APP_DIR))->update($this->cid, [
               'son_type' => dr_array2string($stype)
            ]);
            $this->_json(1, dr_lang('操作成功'));
        }

        \Phpcmf\Service::V()->assign([
            'value' => $stype[$tid],
        ]);
        \Phpcmf\Service::V()->display('son_name.html');exit;

    }
}
